<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="700">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="130px"
      v-loading="formLoading"
    >
      <el-form-item :label="t('batch.fields.batchName')" prop="batchName">
        <el-input
          v-model="formData.batchName"
          :placeholder="t('common.inputTextPlaceholder') + t('batch.fields.batchName')"
        />
      </el-form-item>
      <el-form-item :label="t('batch.fields.year')" prop="year">
        <el-date-picker
          v-model="formData.year"
          type="year"
          value-format="YYYY"
          :placeholder="t('common.selectTextPlaceholder') + t('batch.fields.year')"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item :label="t('batch.fields.recruitTime')" prop="recruitStartTime">
        <el-date-picker
          v-model="recruitTime"
          type="datetimerange"
          value-format="x"
          :disabled-date="disableOccupiedTimeRange1"
          :start-placeholder="
            t('common.selectTextPlaceholder') + t('batch.fields.recruitStartTime')
          "
          :end-placeholder="t('common.selectTextPlaceholder') + t('batch.fields.recruitEndTime')"
          @change="checkOccupiedTimeRange1"
        />
      </el-form-item>
      <el-form-item :label="t('batch.fields.remark')" prop="remark">
        <el-input
          v-model="formData.remark"
          :placeholder="t('common.inputTextPlaceholder') + t('batch.fields.remark')"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading"
        >{{ t('common.ok') }}
      </el-button>
      <el-button @click="dialogVisible = false">{{ t('common.cancel') }}</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { BatchApi, BatchVO } from '@/api/recruit/batch'
import { FormRules } from 'element-plus'

/** 招生计划 表单 */
defineOptions({ name: 'BatchForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  batchName: undefined,
  year: undefined,
  recruitStartTime: undefined,
  recruitEndTime: undefined,
  remark: undefined
})

const recruitTime = computed({
  get() {
    return [formData.value.recruitStartTime, formData.value.recruitEndTime]
  },
  set(value) {
    formData.value.recruitStartTime = value[0] ?? undefined
    formData.value.recruitEndTime = value[1] ?? undefined
  }
})

const formRules = reactive<FormRules>({
  batchName: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('batch.fields.batchName'),
      trigger: 'blur'
    }
  ],
  year: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('batch.fields.year'),
      trigger: 'change'
    }
  ],
  recruitStartTime: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('batch.fields.recruitTime'),
      trigger: 'change'
    }
  ]
})
const formRef = ref() // 表单 Ref

const occupiedTimeRange = ref([]) // 所有不可用的时间段

const checkOccupiedTimeRange1 = (val: number[]) => {
  // 判断所选时间范围内是否含有禁用的时间
  if (val && val[0] && val[1]) {
    const isOccupied = occupiedTimeRange.value.some((item) => {
      return val[0] <= item.startTime && val[1] >= item.endTime
    })
    if (isOccupied) {
      message.error(t('batch.message.occupiedTimeRange'))
      recruitTime.value = [undefined, undefined]
    }
  }
}

const disableOccupiedTimeRange1 = (date: Date) => {
  // 不能选择过去的时间(但不包含今天)和已经被占用的时间
  return (
    date.getTime() < Date.now() - 86400000 ||
    occupiedTimeRange.value.some((item) => {
      return date.getTime() >= item.startTime && date.getTime() <= item.endTime
    })
  )
}

/** 打开弹窗 */
const open = async (type: string, id?: string) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  formLoading.value = true
  // 查询未来所有不可用的时间段
  const response = await BatchApi.getOccupiedTimeRange()
  occupiedTimeRange.value = response
    .filter((item) => item.id !== id)
    .map((item) => {
      return {
        startTime: item.recruitStartTime,
        endTime: item.recruitEndTime
      }
    })

  // 修改时，设置数据
  if (id) {
    try {
      formData.value = await BatchApi.getBatch(id)
    } finally {
      formLoading.value = false
    }
  }
  formLoading.value = false
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  try {
    // 校验表单
    await formRef.value.validate()
  } catch {
    return
  }

  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as BatchVO
    if (formType.value === 'create') {
      await BatchApi.createBatch(data)
      message.success(t('common.createSuccess'))
    } else {
      await BatchApi.updateBatch(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    batchName: undefined,
    year: undefined,
    recruitStartTime: undefined,
    recruitEndTime: undefined,
    remark: undefined
  }
  formRef.value?.resetFields()
}
</script>
